<?php 

/**
 * classe que abstrai o acesso a base de dados para pegar 
 * dados de um coordenador
 */
class DaoCoordenador {
	
	/** */
	public function add($coordenador) {
		drupal_write_record('users', $coordenador);
		
		$role = new stdClass();
		$role->uid = $coordenador->uid;
		$role->rid = $this->getCoordenadorRID();
		
		drupal_write_record('users_roles', $role);
	}
	
	/** */
	public function rm($id) {
		db_query("delete from users where uid = " . $id)->execute();
		db_query("delete from coordenador_aluno where coordenador_id = " . $id)->execute();
		db_query("delete from users_roles where uid = " . $id)->execute();
	}
	
	/** */
	public function get($id) {
		$sql = "select name from users where uid = " . $id;		
		$query = db_query($sql)->fetchAll();
		
		$coordenador = '';
		foreach($query as $row) {
			$coordenador = new stdClass();
			$coordenador->id = $id;
			$coordenador->nome = $row->name;
		}
		
		return $coordenador;
	}
	
	/** */
	public function listar() {
		$sql = "select u.uid, u.name 
						from users as u 
						inner join users_roles as s 
						inner join role as r
						where u.uid = s.uid
						and   s.rid = r.rid
						and   r.rid = " . $this->getCoordenadorRID();
		$query = db_query($sql)->fetchAll();
		
		$coordenadores = array();
		foreach($query as $row) {
			$coordenador = new stdClass();
			$coordenador->id = $row->uid;
			$coordenador->nome = $row->name;
			array_push($coordenadores, $coordenador);
		}
		
		return $coordenadores;
	}
	
	/** Retorna RoleID (rid) do tipo 'coordenador' de usuario*/
	private function getCoordenadorRID() {
		$query = db_select('role')
		->fields('role', array('rid'))
		->condition('name', 'coordenador')
		->execute()
		->fetchAll();
		
		$rid = NULL;
		foreach($query as $row) {
			$rid = $row->rid;
		}
		
		return $rid;
	}
	
}